<script setup lang="ts">
import { ref, PropType, reactive, nextTick } from 'vue';
import { useSetUser } from '@/api/systemUser';
import type { IRoleList } from '../../type';
import type { FormInstance } from 'element-plus';
import type { IUserListInfo, ISetUserParams } from '@/api/systemUser/type';
import { handleMessage } from '@/utils/globalEvent';

const emits = defineEmits(['handleSearch']);
defineProps({
	roleList: {
		type: Array as PropType<IRoleList[]>,
		required: true,
	},
});

const formRef = ref<FormInstance>();
// btnLoading
const btnLoading = ref(false);
const btnLoadingTitle = '操作中';
// 新增用户弹窗
const dialogVisible = ref(false);
// 用户数据
const params = ref<ISetUserParams>({
	id: null,
	name: '',
	password: '',
	role: '',
});
// 用户数据验证
const rules = reactive({
	name: [
		{ required: true, message: '请填写用户名~', trigger: 'blur' },
		{ min: 3, max: 9, message: '用户名长度在3-9位~', trigger: 'blur' },
	],
	password: [
		{ required: true, message: '请填写登录密码~', trigger: 'blur' },
		{ min: 3, max: 12, message: '密码长度在3-12位~', trigger: 'blur' },
	],
	role: [{ required: true, message: '请选择角色~', trigger: 'change' }],
});

// 关闭新增角色弹窗前回调
const handleDialogClose = () => {
	params.value.id = null;
	formRef.value?.resetFields();
	dialogVisible.value = false;
};
// 打开新增角色弹窗
const openDialogVisible = () => {
	dialogVisible.value = true;
};
// 处理编辑
const handleEdit = (data: IUserListInfo) => {
	openDialogVisible();
	nextTick(() => {
		const { id = null, name = '', password = '', role = '' } = data;
		params.value = {
			id,
			name,
			password,
			role,
		};
	});
};

// 点击提交
const clickSubmit = () => {
	formRef.value?.validate(async isOk => {
		if (!isOk) return;
		btnLoading.value = true;
		try {
			const result = await useSetUser(params.value);
			if (!result) return;
			handleMessage(result);
			handleDialogClose();
			emits('handleSearch', { role: '' });
		} catch (error) {
			throw new Error('用户操作未知异常,请联系开发人员');
		} finally {
			btnLoading.value = false;
		}
	});
};

defineExpose({
	openDialogVisible,
	handleEdit,
});
</script>

<template>
	<el-dialog v-model="dialogVisible" title="用户" :before-close="handleDialogClose">
		<el-form ref="formRef" :model="params" :rules="rules" label-width="100px" label-position="left">
			<el-form-item label="用户名：" prop="name">
				<el-input v-model="params.name" />
			</el-form-item>
			<el-form-item label="登陆密码：" prop="password">
				<el-input v-model="params.password" />
			</el-form-item>
			<el-form-item label="角色：" prop="role">
				<el-select v-model="params.role" placeholder="选择角色">
					<el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button v-btn-loading:[btnLoadingTitle]="btnLoading" @click="clickSubmit">提 交</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
